<?php


namespace app\api\controller;


use app\admin\model\SystemUploadfile;
use app\ApiBaseController;

class Reimbuse extends ApiBaseController
{
    /**
     * 批量获取报销记录 0待审核  1已成功  2被驳回
     */
    public function getReimbusesList()
    {
        $status = $this->request->param('status/d', 0);
        if (!in_array($status, [0,1,2])){
            return result(1,'类型不存在');
        }
        $data = \app\admin\model\Reimbuse::where(['uid'=>$this->uid, 'status'=>$status])->select();
        if ($data->isEmpty()){
            return result(0, '', []);
        }
        foreach ($data as $k => $v){
            $data[$k]['true_name'] = $this->user->true_name;
            if ($v['status'] <> 2){
                $data[$k] = $v->hidden(['description']);
            }
            $img_ids_arr = explode(',', $v['img_ids']);
            $images = [];
            foreach ($img_ids_arr as $a){
                $url = SystemUploadfile::where('id', $a)->value('url');
                if (!is_null($url)){
                    $images[] = $url;
                }
            }
            $data[$k]['images'] = $images;
            $v->hidden(['img_ids','update_time']);
        }
        return result(0, '', $data);
    }

    /**
     * 获取单条报销记录
     */
    public function getReimbuse()
    {
        $id = $this->request->param('id/d');
        $row = \app\admin\model\Reimbuse::find($id);
        if (empty($row)){
            return result(1,'报销记录不存在');
        }
        if ($row->uid <> $this->uid){
            return result(1,'只能操作自己的记录');
        }
        $row['true_name'] = $this->user->true_name;
        if ($row['status'] <> 2){
            $row = $row->hidden(['description']);
        }
        $img_ids_arr = explode(',', $row['img_ids']);
        $images = [];
        foreach ($img_ids_arr as $a){
            $url = SystemUploadfile::where('id', $a)->value('url');
            if (!is_null($url)){
                $images[] = $url;
            }
        }
        $row['images'] = $images;
        $row->hidden(['img_ids','update_time']);
        return result(0, '', $row);
    }

    /**
     * 创建报销记录，等待审核
     */
    public function createReimbuse()
    {
        $post = $this->request->post();
        $rule = [
            'amount|报销金额'           =>  'require|float',
            'img_ids|报销凭证'          =>  'require',
            'payment|报销备注'		    =>	'require',
        ];
        $this->apiValidate($post, $rule);
        try{
            \app\admin\model\Reimbuse::create([
                'uid'           =>  $this->uid,
                'amount'        =>  $post['amount'],
                'img_ids'       =>  $post['img_ids'],
                'payment'       =>  $post['payment'],
                'status'        =>  0,
            ]);
        }catch (\Exception $e){
            return result(1, $e->getMessage());
        }
        return result(0,'提交成功');
    }
}